package com.chuantou.yuba.ui.fragment;

import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.adapter.TrendsAdapter;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.CommentResponseTO;
import com.chuantou.yuba.api.to.TrendsCommentTO;
import com.chuantou.yuba.api.to.TrendsDataTO;
import com.chuantou.yuba.api.to.TrendsTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.dao.CacheDao;
import com.chuantou.yuba.pojo.Cache;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.ui.widget.CommentDialog;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.ui.widget.TrendsCommentView;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.LoadCacheTask;
import com.chuantou.yuba.util.UiUtil;

/**
 * 动态通用Fragment
 * 
 * @author dl1001
 * 
 */
public class TrendsFragment extends PaginationListFragment<TrendsDataTO> {
	private static final int MENU_ID_COPY = 1;
	private static final int MENU_ID_DELETE = 2;
	protected static final String TRENDS_CACHE_PREFIX = "trends_list_cache_";
	protected AccountManager mAccountManager;
	protected UserTO mUser;
	protected TrendsAdapter mAdapter;
	private long mTagetUid = 0L;
	private TrendsTO mCacheTrends;
	private TrendsCommentTO mCacheCommentTO;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext.registerReceiver(mTrendsChangeReceiver, new IntentFilter(Constants.INTENT_ACTION_SEND_TRENDS));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mAccountManager = AccountManager.getInstance(mContext);
		mUser = mAccountManager.getUserTO();
		mTagetUid = getArguments() == null ? 0 : getArguments().getLong(Constants.EXTRA_TARGET_UID, 0L);
		View contentView = super.onCreateView(inflater, container, savedInstanceState);
		if (mAdapter == null) {
			mAdapter = new TrendsAdapter(this);
			mListView.setSelector(R.drawable.transparent);
			mListView.setAdapter(mAdapter);
			loadFromCache();
		}
		return contentView;
	}

	protected void loadFromCache() {
		new LoadTrendsCache(mContext, getCacheKey(), TrendsDataTO.class).execute();
	}

	@Override
	public void onResume() {
		super.onResume();
		mUser = mAccountManager.getUserTO();
	}

	public long getCurrentUid() {
		return mUser == null ? -1 : mUser.getUid();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		if (v instanceof TrendsCommentView) {
			TrendsCommentView commentTextView = (TrendsCommentView) v;
			mCacheTrends = commentTextView.getTrends();
			mCacheCommentTO = commentTextView.getComment();
			boolean isMyComment = mCacheCommentTO.getUid() == (mUser != null ? mUser.getUid() : 0L);
			menu.add(0, MENU_ID_COPY, 0, R.string.copy);
			if (isMyComment) {
				menu.add(0, MENU_ID_DELETE, 0, R.string.delete);
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (UiUtil.isFastDoubleClick())
			return super.onContextItemSelected(item);
		switch (item.getItemId()) {
		case MENU_ID_COPY:
			UiUtil.copy(mContext, mCacheCommentTO.getContent(), true);
			break;
		case MENU_ID_DELETE:
			delelteComment(mCacheTrends, mCacheCommentTO);
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	private BroadcastReceiver mTrendsChangeReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			load(1);
		}
	};

	public void onDestroy() {
		mContext.unregisterReceiver(mTrendsChangeReceiver);
		super.onDestroy();
	};

	private void delelteComment(final TrendsTO trendsTO, final TrendsCommentTO commentTO) {
		String url = UriHelper.getDeleteTrendsCommentUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_TOKEN, mUser.getToken());
		params.put(UriHelper.PARAMS_UID, String.valueOf(mUser.getUid()));
		params.put(UriHelper.PARAMS_ID, String.valueOf(commentTO.getId()));
		GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (response != null) {
					if (response.isSuccess()) {
						List<TrendsCommentTO> comments = trendsTO.getComments();
						if (comments != null) {
							comments.remove(commentTO);
							trendsTO.setCommentCount(trendsTO.getCommentCount() - 1);
							mAdapter.notifyDataSetChanged();
						}
					} else if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
						Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
					}
				}
			}
		}, null, params, BaseTO.class);
		RequestManager.startRequest(mContext, request);
	}

	@Override
	protected BaseGsonRequest<TrendsDataTO> getRequest(Listener<TrendsDataTO> listener, ErrorListener errorListener) {
		String token = mUser != null ? mUser.getToken() : null;
		long uid = mUser != null ? mUser.getUid() : 0;
		return RequestManager.getTrendsListRequest(listener, errorListener, token, uid, mTagetUid, 1, Constants.DEFAULT_PAGE_SIZE);
	}

	@Override
	public void onResponse(TrendsDataTO response) {
		if (getActivity() != null) {
			super.onResponse(response);
			if (response != null) {
				List<TrendsTO> trends = response.getTrendsList();
				// 第一页
				if (response.getCurrentPage() <= 1) {
					// 保存到本地数据库缓存
					CacheDao.addOrUpdateCache(mContext, getCacheKey(), response);
					mAdapter.clear();
				}
				mAdapter.addTrendsList(trends);
			}

			if (mAdapter.getCount() <= 0) {
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			}
			mAdapter.notifyDataSetChanged();
		}
	}

	class LoadTrendsCache extends LoadCacheTask<TrendsDataTO> {

		public LoadTrendsCache(Context context, String cacheKey, Class<TrendsDataTO> clazz) {
			super(context, cacheKey, clazz);
		}

		@Override
		protected void onPostExecute(Cache<TrendsDataTO> result) {
			super.onPostExecute(result);
			TrendsDataTO dataTO = result == null ? null : result.getData();
			List<TrendsTO> trendsTO = dataTO == null ? null : dataTO.getTrendsList();
			mAdapter.addTrendsList(trendsTO);
			mAdapter.notifyDataSetChanged();
			startRequest();
		}
	}

	protected String getCacheKey() {
		if (mTagetUid <= 0) {
			return TRENDS_CACHE_PREFIX.concat("all");
		} else {
			return TRENDS_CACHE_PREFIX.concat(String.valueOf(mTagetUid));
		}
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.no_trends_content);
	}

	/**
	 * 显示评论对话框
	 * 
	 * @param trendsId
	 * @param replyUid
	 *            >0时表示回复某个用户
	 */
	public void showReplyPopup(final TrendsTO trends, final long replyUid, final String replyNickname) {
		if (UiUtil.isFastDoubleClick())
			return;
		if (!mAccountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			if (mUser.isExpired()) {
				Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				final HashMap<String, String> returnData = new HashMap<String, String>();
				final CommentDialog popup = new CommentDialog(getActivity(), mUser, trends.getId(), replyUid, replyNickname, returnData);
				// popup.setOnDismissListener(new
				// DialogInterface.OnDismissListener() {
				//
				// @Override
				// public void onDismiss(DialogInterface dialog) {
				// UiUtil.hideInputKeyboard(mContext, mListView);
				// }
				// });
				// popup.setCanceledOnTouchOutside(true);
				Listener<CommentResponseTO> listener = new Listener<CommentResponseTO>() {

					@Override
					public void onResponse(CommentResponseTO response) {
						if (getActivity() != null) {
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(mContext, R.string.comment_send_success, Toast.LENGTH_SHORT).show();
									TrendsCommentTO commentTO = new TrendsCommentTO();
									String comment = returnData.get(Constants.EXTRA_DATA);
									commentTO.setContent(comment);
									commentTO.setId(response.getId());
									commentTO.setNickname(mUser.getUsername());
									commentTO.setReplyNickname(replyNickname);
									commentTO.setReplyUid(replyUid);
									commentTO.setTrendsId(trends.getId());
									commentTO.setUid(mUser.getUid());
									trends.addComment(commentTO);
									mAdapter.notifyDataSetChanged();
									popup.dismiss();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? getString(R.string.comment_send_failed) : msg;
										Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(mContext, R.string.comment_send_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				};
				popup.setListener(listener);
				FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				popup.show(ft, popup.getClass().getName());
			}
		}
	}

	/**
	 * 赞动态
	 * 
	 * @param trendsTO
	 */
	public void likeTrends(final ImageView likeBtnView, final TextView likeCountView, final TrendsTO trendsTO) {
		if (!mAccountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		String url = UriHelper.getLikeTrendsUrl();
		final boolean isLiked = trendsTO.isLike();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_UID, String.valueOf(mUser.getUid()));
		params.put(UriHelper.PARAMS_TOKEN, mUser.getToken());
		params.put(UriHelper.PARAMS_ID, String.valueOf(trendsTO.getId()));
		params.put(UriHelper.PARAMS_ACTION, isLiked ? "del" : "do");
		GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (getActivity() != null) {
					likeBtnView.setClickable(true);
					if (response == null) {
						Toast.makeText(mContext, R.string.operate_failed, Toast.LENGTH_SHORT).show();
					} else {
						if (response.isSuccess()) {
							if (isLiked) {
								trendsTO.setHasLiked(false);
								trendsTO.setLikeCount(trendsTO.getLikeCount() - 1);
							} else {
								trendsTO.setHasLiked(true);
								trendsTO.setLikeCount(trendsTO.getLikeCount() + 1);
							}
							likeBtnView.setSelected(!isLiked);
							int likeCount = trendsTO.getLikeCount();
							if (likeCount > 0) {
								likeCountView.setVisibility(View.VISIBLE);
							} else {
								likeCountView.setVisibility(View.GONE);
							}
							likeCountView.setText(String.valueOf(likeCount));
						} else if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
							Toast.makeText(getActivity(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
							LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
						} else {
							String msg = response.getMsg();
							msg = TextUtils.isEmpty(msg) ? mContext.getString(R.string.operate_failed) : msg;
							Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
						}
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (getActivity() != null) {
					Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
					likeBtnView.setClickable(true);
				}
			}
		}, params, BaseTO.class);
		RequestManager.startRequest(mContext, request);
	}

	public void deleteTrends(final TrendsTO trendsTO) {
		if (!mAccountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle(R.string.prompt);
		builder.setMessage(R.string.message_delete_prompt);
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String url = UriHelper.getDeleteTrendsUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_UID, String.valueOf(mUser.getUid()));
				params.put(UriHelper.PARAMS_TOKEN, mUser.getToken());
				params.put(UriHelper.PARAMS_ID, String.valueOf(trendsTO.getId()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (getActivity() != null) {
							if (response == null) {
								Toast.makeText(mContext, R.string.operate_failed, Toast.LENGTH_SHORT).show();
							} else {
								if (response.isSuccess()) {
									mAdapter.removeTrends(trendsTO);
									mAdapter.notifyDataSetChanged();
								} else if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
									Toast.makeText(getActivity(), R.string.message_token_expired, Toast.LENGTH_SHORT).show();
									LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
								} else {
									String msg = response.getMsg();
									msg = TextUtils.isEmpty(msg) ? mContext.getString(R.string.operate_failed) : msg;
									Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
								}
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (getActivity() != null) {
							Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(mContext, request);
			}
		});
		builder.create().show();
	}

}
